package com.qf.staff.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qf.common.base.exception.ServiceException;
import com.qf.common.base.result.ResultCode;
import com.qf.common.db.utils.PageCommonBeanUtils;
import com.qf.staff.common.qo.StockQo;
import com.qf.staff.common.vo.StockVo;
import com.qf.staff.mapper.StockMapper;
import com.qf.staff.pojo.Stock;
import com.qf.staff.service.StockService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;

@Service
@Slf4j
public class StockServiceImpl implements StockService {
    @Resource
    StockMapper stockMapper;

    @Override
    public IPage<StockVo> list(int page, int size) {
        try {
            return PageCommonBeanUtils.copyPage(stockMapper.selectPage(new Page<>(page, size), null),
                    new Page<>(), StockVo::new);
        } catch (Exception e) {
            throw new ServiceException(ResultCode.QUERY_ERROR);
        }
    }

    @Override
    public int delete(StockQo stockQo) {
        try {
            Stock stock = new Stock();
            BeanUtils.copyProperties(stockQo, stock);
            return stockMapper.updateByStatus(stock);
        } catch (BeansException e) {
            throw new ServiceException(ResultCode.DELETE_ERROR);
        }
    }


    @Override
    public int modify(StockQo stockQo) {
        try {
            Stock stock = new Stock();
            BeanUtils.copyProperties(stockQo, stock);
            return stockMapper.updateById(stock);
        } catch (BeansException e) {
            throw new ServiceException(ResultCode.UPDATE_ERROR);
        }
    }

    @Override
    public int add(StockQo stockQo) {
        try {
            Integer stockNumber = stockQo.getStockNumber();
            QueryWrapper<Stock> qw = new QueryWrapper<>();
            qw.eq("stock_number", stockNumber);
            Stock stock1 = stockMapper.selectOne(qw);
            if (!ObjectUtils.isEmpty(stock1)) {
                stockQo.setStockNumber(stockQo.getStockNumber() + stock1.getStockNumber());
                Stock stock = new Stock();
                BeanUtils.copyProperties(stockQo, stock);
                return stockMapper.insert(stock);
            } else {
                Stock stock = new Stock();
                BeanUtils.copyProperties(stockQo, stock);
                return stockMapper.insert(stock);
            }
        } catch (BeansException e) {
            throw new ServiceException(ResultCode.INSERT_ERROR);
        }
    }
}
